﻿using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VSSDK.Tools.VsIdeTesting;
using System;
using System.Linq;
using System.Runtime.InteropServices;

namespace Sasa.QualityTools.CodeAnalysis.FxCopIntegrator.Tests.Integration.Instruments
{
    public static class PackageLoader
    {
        public static Package LoadPackage(string packageGuid)
        {
            var shell = VsIdeTestHostContext.ServiceProvider.GetService(typeof(SVsShell)) as IVsShell;
            var guid = new Guid(packageGuid);
            IVsPackage package;
            shell.LoadPackage(ref guid, out package);

            return (Package)package;
        }

        public static TPackage LoadPackage<TPackage>()
            where TPackage : Package
        {
            var attr = typeof(TPackage).GetCustomAttributes(typeof(GuidAttribute), false).FirstOrDefault() as GuidAttribute;
            if (attr == null)
            {
                throw new InvalidOperationException();
            }

            var shell = VsIdeTestHostContext.ServiceProvider.GetService(typeof(SVsShell)) as IVsShell;
            var guid = new Guid(attr.Value);
            IVsPackage package;
            shell.LoadPackage(ref guid, out package);

            return package as TPackage;
        }
    }
}
